<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="试卷名称" prop="parperName">
        <el-input v-model="queryParams.parperName" placeholder="请输入试卷名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.parper_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="创建者" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建者" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="daterangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['exa:parper:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['exa:parper:edit']">修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['exa:parper:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['exa:parper:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="parperList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="试卷名称" align="center" prop="parperName" />
      <el-table-column label="试题数量" align="center" prop="questionNum" />
      <el-table-column label="试卷分数" align="center" prop="parperScore" />
      <el-table-column label="通过分数" align="center" prop="passScore" />
      <el-table-column label="答题时间" align="center" prop="answeringTime" />
      <!-- <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.parper_status" :value="scope.row.status" />
        </template>
</el-table-column> -->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['exa:parper:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['exa:parper:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改试卷管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1080px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="top">
          <div class="t">
            <el-form-item label="试卷标题" prop="parperName">
              <el-input v-model="form.exaParper.parperName" placeholder="请输入试卷名称" />
            </el-form-item>
          </div>

          <div class="b">
            <el-button type="primary" @click="addTopic">添加题目</el-button>
            <el-button type="info">预览试卷</el-button>
            <!-- <el-button type="primary">保存试卷</el-button> -->
          </div>
        </div>

        <div class="bottom_form">
          <!-- 左侧试题 -->
          <div class="test-paper">
            <!-- 题目列表 -->
            <div class="test_paper_item" v-for="(item, index) in form.exaClassVoList" :key="index">
              <!-- 试题标题 -->
              <div class="paper_title">
                <div class="paper_title_txt">{{ item.className }}</div>
                <div class="paper_title_btn">
                  <!-- 在试题列表中传入索引 -->
                  <el-button type="text" @click="addQuestions(item, index)" icon="el-icon-circle-plus"
                    plan>选择试题</el-button>
                  <el-button type="text" icon="el-icon-edit" @click="editTopic(item, index)" plan>编辑</el-button>
                  <el-button type="text" icon="el-icon-error" @click="removeTopic(index)" plan>删除</el-button>
                </div>
              </div>

              <div class="paper_gross">

                <!-- 试题内容 -->
                <div class="paper_gross_l_info" v-for="(question, qIndex) in item.exaClassQuestionList" :key="qIndex">
                  <!-- 试题标题 -->
                  <div class="paper_gross_l_info_top">
                    <div class="paper_gross_l_info_top_title">{{ qIndex + 1 }}、 {{ question.title }}</div>
                    <div class="paper_gross_l_info_top_fenshu">（{{ question.score }}分）</div>
                  </div>

                  <div class="paper_gross_l_info_bottom_flex">

                    <!-- 左侧试题内容 -->
                    <div class="paper_gross_l_info_bottom_l">
                      <div class="paper_gross_l_info_bottom">
                        <div class="paper_gross_l_info_bottom_item"
                          :class="{ paper_gross_l_info_bottom_item_hover: option.rorw }"
                          v-for="(option, oIndex) in question.options" :key="oIndex">
                          {{ oIndex + 1 }}. {{ option.content }}
                        </div>
                      </div>
                    </div>

                    <!-- 右侧操作按钮 -->
                    <div class="paper_gross_l_info_bottom_r">
                      <el-button type="info" size="mini" plain @click="removeQuestion(item, qIndex)">删除</el-button>
                      <el-button type="info" size="mini" plain @click="moveUpQuestion(item, qIndex)"
                        :disabled="qIndex === 0">上移</el-button>
                      <el-button type="info" size="mini" plain @click="moveDownQuestion(item, qIndex)"
                        :disabled="qIndex === item.exaClassQuestionList.length - 1">下移</el-button>
                      <el-button type="info" size="mini" plain @click="moveFirstQuestion(item, qIndex)"
                        :disabled="qIndex === 0">最前</el-button>
                      <el-button type="info" size="mini" plain @click="moveLastQuestion(item, qIndex)"
                        :disabled="qIndex === item.exaClassQuestionList.length - 1">最后</el-button>
                    </div>
                  </div>
                </div>

              </div>
            </div>
          </div>

          <!-- 右侧分数 -->
          <div class="paper-score">
            <div class="all">题目总数：{{ totalQuestionCount }}</div>
            <div class="gross">试卷总分：{{ totalScore }}</div>
          </div>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保存试卷</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加题目弹窗 -->
    <el-dialog title="添加题目" :visible.sync="open2" width="480px" append-to-body>
      <el-form ref="form2" :model="form2" :rules="rules2" label-width="80px">
        <el-form-item label="题目标题" prop="className">
          <el-input v-model="form2.className" placeholder="请输入试卷名称" />
        </el-form-item>

        <el-form-item label="选择类型" prop="classId">
          <el-select v-model="form2.classId" placeholder="请选择状态" clearable>
            <el-option v-for="dict in dict.type.question_type" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择试题弹窗 -->
    <el-dialog title="添加题目" :visible.sync="open3" width="480px" append-to-body>
      <el-form :model="queryParams2" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="试卷名称" prop="title"></el-form-item>
      </el-form>
      <el-table v-loading="loading2" :data="questionList" @selection-change="handleSelectionChange">
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column label="试题ID" align="center" prop="id" />
        <el-table-column label="试题标题" align="center" prop="title" />
        <el-table-column label="试题分数" align="center" prop="score" />
        <el-table-column type="selection" width="55" align="center" :selectable="checkSelectable" />
      </el-table>
      <!-- 分页器 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams2.pageNum"
        :limit.sync="queryParams2.pageSize" @pagination="getList" />


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm3">确 定</el-button>
        <el-button @click="cancel3">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listParper, getParper, delParper, addParper, updateParper, saveOrUpdate } from "@/api/exa/parper"
import { listBank } from "@/api/exa/bank"
import { getBank } from "@/api/exa/bank"
import { listOptions } from "@/api/exa/options"

import { get } from "sortablejs"
export default {
  name: "Parper",
  dicts: ['parper_status', 'question_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      loading2: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试卷管理表格数据
      parperList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      open3: false,
      // 备注时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parperName: null,
        createBy: null,
        createTime: null,
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        score: null,
        type: null,
        createBy: null,
      },
      // 表单参数
      form: {
        exaParper: {
          id: null,
          parperName: null,
          questionNum: null,
          parperScore: null,
        },
        exaClassVoList: []
      },
      form2: {},
      formList: {},
      // 表单校验
      rules: {},
      rules2: {},
      questionList: [], // 试题列表
      currentClassIndex: -1, // 添加当前操作的题目索引
      exaQuestionOptionsList: [], // 试题答案列表
      editTopicIndex: null, // 当前编辑的大题索引
      editTopicForm: {
        className: '',
        classId: ''
      },
    }
  },
  created() {
    this.getList()
  },

  computed: {
    // 题目总数
    totalQuestionCount() {
      return this.form.exaClassVoList.reduce((sum, group) => {
        return sum + (group.exaClassQuestionList ? group.exaClassQuestionList.length : 0);
      }, 0);
    },
    // 试卷总分
    totalScore() {
      return this.form.exaClassVoList.reduce((sum, group) => {
        if (!group.exaClassQuestionList) return sum;
        return sum + group.exaClassQuestionList.reduce((s, q) => s + (Number(q.score) || 0), 0);
      }, 0);
    }
  },
  methods: {

    /** 查询试卷管理列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0]
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1]
      }
      listParper(this.queryParams).then(response => {
        this.parperList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 更新总分和总题
    // updatePaperSummary() {
    //   this.form.exaParper.questionNum = this.totalQuestionCount;
    //   this.form.exaParper.parperScore = this.totalScore;
    // },

    // 添加题目
    addTopic() {
      console.log("添加题目");

      this.open2 = true

    },

    getlistBank() {
      // 添加类型判断
      if (!this.queryParams2.type) {
        this.$modal.msgError("请先选择试题类型");
        return;
      }
      this.loading2 = true;
      listBank(this.queryParams2).then(res => {
        console.log("试题列表", res);
        this.loading2 = false;
        if (res.code == 200 && res.rows.length > 0) {
          // this.$modal.msgSuccess("试题列表加载成功");
          this.questionList = res.rows;
        } else {
          this.$modal.msgWarning("没有可用的试题");
        }
      })
    },

    // 选择试题
    addQuestions(item, index) {
      if (!item || !item.classId) {
        this.$modal.msgError("试题类型不能为空");
        return;
      }

      this.currentClassIndex = index;
      this.queryParams2.type = item.classId;
      this.getlistBank();
      this.open3 = true;
    },

    /** 选择试题后的试题答案获取 */
    getAnswerForQuestion(questionId, qIndex, currentClass) {
      getBank(questionId).then(response => {
        listOptions({ questionId: response.data.id }).then(res => {
          console.log('res', res);

          // 赋值到对应题目的 options 字段
          this.$set(currentClass.exaClassQuestionList[qIndex], 'options', res.rows);
        });
      });
    },

    // 编辑大题
    editTopic(item, index) {
      this.editTopicIndex = index;
      this.editTopicForm = {
        className: item.className,
        classId: item.classId
      };
      this.$prompt('请输入新的题目名称', '编辑题目', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: item.className,
        inputPattern: /.+/,
        inputErrorMessage: '题目名称不能为空'
      }).then(({ value }) => {
        this.form.exaClassVoList[index].className = value;

        // 类型修改
        // this.form.exaClassVoList[index].classId = ...;
        // this.updatePaperSummary && this.updatePaperSummary();
      }).catch(() => { });
    },

    // 删除大题
    removeTopic(index) {
      this.$confirm('确定要删除该题型及其下所有试题吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.form.exaClassVoList.splice(index, 1);
        // this.updatePaperSummary && this.updatePaperSummary(); 
      }).catch(() => { });
    },

    // 删除试题
    removeQuestion(item, qIndex) {
      this.$confirm('确定要删除该题目吗？', '提示', {
        type: 'warning'
      }).then(() => {
        item.exaClassQuestionList.splice(qIndex, 1);
        this.$message.success('删除成功');
      }).catch(() => { });
    },

    // 上移
    moveUpQuestion(item, qIndex) {
      if (qIndex > 0) {
        const list = item.exaClassQuestionList;
        const temp = list[qIndex];
        list.splice(qIndex, 1);
        list.splice(qIndex - 1, 0, temp);
      }
    },
    // 下移
    moveDownQuestion(item, qIndex) {
      const list = item.exaClassQuestionList;
      if (qIndex < list.length - 1) {
        const temp = list[qIndex];
        list.splice(qIndex, 1);
        list.splice(qIndex + 1, 0, temp);
      }
    },

    // 最前
    moveFirstQuestion(item, qIndex) {
      if (qIndex > 0) {
        const list = item.exaClassQuestionList;
        const temp = list.splice(qIndex, 1)[0];
        list.unshift(temp);
      }
    },

    // 最后
    moveLastQuestion(item, qIndex) {
      const list = item.exaClassQuestionList;
      if (qIndex < list.length - 1) {
        const temp = list.splice(qIndex, 1)[0];
        list.push(temp);
      }
    },

    // 判断是否可选
    checkSelectable(row) {
      // 获取当前操作的题目
      const currentClass = this.form.exaClassVoList[this.currentClassIndex];
      if (!currentClass) return true;

      // 检查试题是否已经添加过
      const isExist = currentClass.exaClassQuestionList.some(item => item.id === row.id);
      return !isExist; // 如果已存在返回 false 禁用选择
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    cancel2() {
      this.open2 = false
      this.form2 = {}
    },

    cancel3() {
      this.open3 = false;
      this.formList = [];
      this.currentClassIndex = -1;
    },

    // 表单重置
    reset() {
      this.form = {
        exaParper: {
          id: null,
          parperName: null,
          questionNum: null,
          parperScore: null,
        },
        exaClassVoList: []
      }
      this.resetForm("form")
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      // console.log("选中数据", selection);
      this.formList = selection

      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length

    },


    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加试卷管理"
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getParper(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改试卷管理"
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateParper(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addParper(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    // 添加题目提交按钮
    submitForm2() {
      this.$refs["form2"].validate(valid => {
        if (valid) {
          // 创建新对象，避免引用原对象
          const newTopic = {
            className: this.form2.className,
            classId: this.form2.classId,
            exaClassQuestionList: [] // 添加试题列表数组
          }

          this.form.exaClassVoList.push(newTopic) // 将新对象添加到试卷中
          this.$modal.msgSuccess("题目添加成功")
          console.log(this.form.exaClassVoList);

          // 重置表单
          this.form2 = {
            className: '',
            classId: ''
          }
          this.open2 = false
        }
      })
    },
    // 选择试题提交按钮
    submitForm3() {
      if (this.currentClassIndex === -1) {
        this.$modal.msgError("请先选择题目类型");
        return;
      }

      if (!this.formList || this.formList.length === 0) {
        this.$modal.msgWarning("请选择要添加的试题");
        return;
      }

      // 将选中的试题添加到对应题目的试题列表中
      const currentClass = this.form.exaClassVoList[this.currentClassIndex];
      console.log(currentClass);

      if (currentClass) {
        // 将选中的试题添加到试题列表
        this.formList.forEach(item => {
          currentClass.exaClassQuestionList.push({
            id: item.id,
            title: item.title,
            score: item.score,
            type: item.type,
            options: [] // 新增
          });
          this.getAnswerForQuestion(item.id, currentClass.exaClassQuestionList.length - 1, currentClass);
        });


        this.$modal.msgSuccess("试题添加成功");
        this.open3 = false; // 关闭弹窗
        this.formList = []; // 清空选中数据
        this.currentClassIndex = -1; // 重置当前操作的题目索引
        console.log("试题添加后", this.form);

      }
    },

    /** 列表删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除试卷管理编号为"' + ids + '"的数据项？').then(function () {
        return delParper(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('exa/parper/export', {
        ...this.queryParams
      }, `parper_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog {
  background-color: #F1F4F6;

  .top {
    width: 100%;
    height: 100%;
    margin-bottom: 20px;
    padding: 10px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .t {
      height: 36px;

      .el-form-item {
        height: 36px !important;
      }
    }
  }

  .bottom_form {
    width: 100%;
    min-height: 400px;
    display: flex;
    justify-content: space-between;
    // align-items: center;

    .test-paper {
      width: 80%;
      min-height: 400px;
      padding: 20px;
      box-sizing: border-box;
      background-color: #fff;

      .test_paper_item {
        border-bottom: 1px solid #f2f2f2;
        margin-bottom: 20px;

        .paper_title {
          width: 100%;
          height: 60px;
          line-height: 60px;
          // background-color: #000;
          // border-bottom: 2px dashed #ccc;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .paper_title_txt {
            font-size: 24px;
            font-weight: 700;
          }

          .paper_title_btn {
            width: 33%;
            // background-color: #ccc;
            padding: 0 10px;
            box-sizing: border-box;
            display: flex;
            justify-content: space-between;

            .el-button {
              color: #7F7F7F !important;
            }
          }
        }

        .paper_gross {
          min-height: 160px;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          // align-items: center;
          border-top: 1px solid #f2f2f2;
          border-top: 2px dashed #ccc;
          border-bottom: 2px dashed #ccc;
          margin-bottom: 40px;
          padding-bottom: 30px;
          box-sizing: border-box;

          // background-color: #000;

          .paper_gross_l_info {
            margin-top: 20px;
            padding: 0 20px;
            box-sizing: border-box;

            .paper_gross_l_info_top {
              width: 440px;
              margin-bottom: 20px;
              padding-right: 15px;
              box-sizing: border-box;
              font-size: 18px;
              display: flex;
              justify-content: space-between;
              align-items: center;
            }

            .paper_gross_l_info_bottom_flex {
              display: flex;
              justify-content: space-between;
              align-items: end;

              .paper_gross_l_info_bottom_l {
                width: 440px;

                .paper_gross_l_info_bottom {
                  width: 400px !important;
                  padding: 0 20px;
                  box-sizing: border-box;
                  border-radius: 5px;

                  .paper_gross_l_info_bottom_item {
                    width: 100%;
                    line-height: 40px;
                    font-size: 16px;
                    border: 1px solid #F0F0F0;
                    // background-color: #000;
                    margin-top: 10px;
                    padding: 5px 10px;
                    box-sizing: border-box;
                    border-radius: 5px;
                    color: #333;
                    cursor: pointer;

                    // &:hover {
                    //   background-color: #FFF3F3;
                    //   border-color: #ECACAC;
                    // }
                  }

                  .paper_gross_l_info_bottom_item_hover {
                    background-color: #FFF3F3;
                    border-color: #ECACAC;
                  }
                }
              }

              .paper_gross_l_info_bottom_r {
                width: 300px;
                // overflow: hidden;
                display: flex;
                align-items: end;
              }
            }
          }
        }
      }


    }

    .paper-score {
      width: 20%;
      height: 160px;
      margin-left: 10px;
      padding: 0 20px;
      box-sizing: border-box;
      background-color: #fff;
      color: #7F7F7F;

      .all,
      .gross {
        line-height: 80px;
        font-size: 18px;
      }

      .all {
        border-bottom: 1px solid #ebe1e1;
      }
    }
  }
}
</style>